<?php

namespace App\Services;

use App\Exceptions\AuthException;
use App\Models\UserModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class AuthService extends BaseService
{
    /**
     * 查询指定用户名的用户
     *
     * @param string $name
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public function getUserByName(string $name)
    {
        return UserModel::query()
            ->select('id', 'name', 'role', 'created_at')
            ->where('name', $name)
            ->where('deleted_at', 0)
            ->first();
    }

    private function getPasswordById(int $id)
    {
        return UserModel::query()
            ->select('password')
            ->where('id', $id)
            ->first();
    }

    private function transferColumns(array $data): array
    {
        return [
            'name' => $data['name'] ?? '',
            'password' => Hash::make($data['password']),
            'role' => UserModel::ROLE_MEMBER,
            'created_at' => time(),
            'updated_at' => time()
        ];
    }

    /**
     * 注册
     *
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder|Model
     * @throws AuthException
     */
    public function storeUser(array $data)
    {
        $user = $this->getUserByName($data['name']);
        if ($user) {
            throw new AuthException('会员已存在', 403);
        }

        $temp = $this->transferColumns($data);

        return UserModel::query()->create($temp);
    }

    /**
     * 登录
     *
     * @param array $data
     * @return bool
     * @throws AuthException
     */
    public function loginByName(array $data): bool
    {
        $user = $this->getUserByName($data['name']);
        if (! $user) {
            throw new AuthException('会员不存在，请先注册', 404);
        }

        $userTemp = $this->getPasswordById($user->id);

        if (! Hash::check($data['password'], $userTemp->password)) {
            throw new AuthException('密码错误，请重试', 401);
        }

        auth()->login($user);

        return true;
    }
}
